<template>
    <LayoutWrap class="role">
        <el-form :inline="true" :model="formSearch" ref="ruleForm" class="demo-form-inline">
            <el-form-item prop="name" label="角色名称">
                <el-input
                    v-model="formSearch.name"
                    placeholder="请输入角色名称"
                    :style="{width: formInputWidth}"
                    clearable
                    @change="handleSearch"
                    @keyup.enter="handleSearch"
                ></el-input>
            </el-form-item>
            <!-- <el-form-item>
                <el-button type="default" @click="$refs['ruleForm'].resetFields()">重置</el-button>
                <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-form-item> -->
        </el-form>
        <ul v-if="isOperation" class="list-head">
            <li class="list-head-item">
                <el-button @click="handleAdd" :disabled="!isOperation" type="primary">添加角色</el-button>
            </li>
        </ul>
        <el-table :data="tableData" border :default-sort="{prop: 'date', order: 'descending'}" style="width: 100%">
            <el-table-column prop="name" label="角色名称"> </el-table-column>
            <el-table-column prop="id" label="id"> </el-table-column>
            <el-table-column prop="operator" label="创建人">
                <template v-slot="{row}">{{ row.operator.name }}</template>
            </el-table-column>
            <el-table-column prop="date" label="创建时间">
                <template v-slot="{row}">
                    {{ moment(row.date).format(THE_MOMENT_YYMMDD_HHMMSS) }}
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注"> </el-table-column>
            <el-table-column align="center" label="操作">
                <template v-slot="{row}">
                    <el-button @click="handleDetail(row)" type="text">
                        查看
                    </el-button>
                    <template v-if="isOperation">
                        <el-button @click="handleEdit(row)" :disabled="row.isRoot || !isOperation" type="text">
                            编辑
                        </el-button>
                        <el-button
                            @click="handleShowDeleteDialog(row)"
                            :disabled="row.isRoot || !isOperation"
                            type="text"
                        >
                            删除
                        </el-button>
                    </template>
                </template>
            </el-table-column>
        </el-table>
        <Pagination
            :page-size.sync="formSearch.pageSize"
            :page.sync="formSearch.page"
            :total="formSearch.count"
            @change="onChangePage"
        />
        <RoleDialog
            v-if="isOperation"
            title="添加角色"
            @on-ok="getList"
            :data-source="dataSourceAdd"
            :visible.sync="roleDialogVisible"
        >
        </RoleDialog>
        <RoleDialog
            title="查看角色"
            @on-ok="getList"
            :data-source="dataSourceDetail"
            :visible.sync="roleDialogVisibleDetail"
        >
        </RoleDialog>
        <RoleDialog
            v-if="isOperation"
            title="编辑角色"
            @on-ok="getList"
            :data-source="dataSourceEdit"
            :visible.sync="roleDialogVisibleEdit"
        >
        </RoleDialog>
        <TheElDialog v-if="isOperation" title="删除角色" :visible.sync="dialogVisible">
            <span>你确定删除 {{ currentRow.name }} 吗？</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button :loading="dialogLoading" type="primary" @click="handleDelete(currentRow)">确 定</el-button>
            </span>
        </TheElDialog>
    </LayoutWrap>
</template>
<script>
import {formInputWidth} from '@/styles/variables.scss';
import {getPermissions} from '@/api/common';
import {getRoles, postRoles, putRoles, deleteRoles, getRolesByIdPermission} from '@/api/role';
import moment from 'moment';
import RoleDialog from './RoleDialog';
import {mixinIsOperation} from '@/mixins';
import {THE_MOMENT_YYMMDD_HHMMSS} from '@/utils/constant';

export default {
    name: 'auth',
    components: {
        RoleDialog
    },
    mixins: [mixinIsOperation],
    data() {
        return {
            THE_MOMENT_YYMMDD_HHMMSS,
            moment,
            formInputWidth,
            // 检索数据
            formSearch: {
                name: '',
                count: 0, // 总条数
                pageSize: 10, // 一页多少条
                page: 1 // 当前第几页
            },
            // 新建弹窗
            roleDialogVisible: false,
            // 编辑
            roleDialogVisibleEdit: false,
            // 查看详情
            roleDialogVisibleDetail: false,
            // 删除
            dialogVisible: false,
            // 操作当前行数据
            currentRow: {},
            // 删除用户loading
            dialogLoading: false,
            // 添加角色
            dataSourceAdd: {
                name: '',
                remark: '',
                modelPermission: {
                    childModules: [],
                    functionMap: {},
                    parentModules: [],
                    selectedFunctions: [],
                    selectedModules: []
                }
            },
            // 查看详情
            dataSourceDetail: {
                id: undefined,
                name: '',
                remark: '',
                modelPermission: {
                    childModules: [],
                    functionMap: {},
                    parentModules: [],
                    selectedFunctions: [],
                    selectedModules: []
                }
            },
            // 编辑
            dataSourceEdit: {
                id: undefined,
                name: '',
                remark: '',
                modelPermission: {
                    childModules: [],
                    functionMap: {},
                    parentModules: [],
                    selectedFunctions: [],
                    selectedModules: []
                }
            },
            // 列表数据
            tableData: [
                // {
                //     id: '22314',
                //     name: '管理员',
                //     operator: {
                //         id: '',
                //         name: 'mrli'
                //     },
                //     create_time: '2019-02-03 01:02:01',
                //     remark: ''
                // },
                // {
                //     id: '222',
                //     name: '管理员',
                //     operator: {
                //         id: '',
                //         name: 'mrli'
                //     },
                //     create_time: '2019-02-03 01:02:01',
                //     remark: ''
                // }
            ],
            // 权限数据
            permission: {}
        };
    },
    created() {
        this.getList();
        this.handleGetPermissions();
    },
    methods: {
        onChangePage(value) {
            this.formSearch = {...this.formSearch, ...value};
            this.getList();
        },
        // 获取权限 列表
        handleGetPermissions() {
            getPermissions().then(({data: res}) => {
                if (res.status === 200) {
                    const {childModules, functionMap, parentModules, selectedFunctions, selectedModules} = res;
                    this.permission = {childModules, functionMap, parentModules, selectedFunctions, selectedModules};
                }
            });
        },
        handleSearch() {
            this.formSearch = {...this.formSearch, page: 1, pageSize: 10};
            this.getList();
        },
        getList() {
            const {name, pageSize, page} = this.formSearch;
            getRoles({name, pageSize, page}).then(({data: res}) => {
                if (res.status === 200) {
                    const {data = [], statData, page, pageSize, count} = res;
                    this.tableData = data;
                    this.formSearch = {...this.formSearch, page, pageSize, count};
                }
            });
        },
        // 添加角色
        handleAdd() {
            this.roleDialogVisible = true;
            const permission = {...this.permission};
            this.dataSourceAdd = {...this.dataSourceAdd, modelPermission: permission};
        },
        // 通过角色id获取角色权限
        async handleGetRolesByIdPermission(roleId, name, remark) {
            const {
                data: {data, status}
            } = await getRolesByIdPermission(roleId);
            if (status === 200) {
                return {id: roleId, name, remark, modelPermission: data};
            }
            return {id: roleId, name, remark, modelPermission: {}};
        },
        // 查看详情
        async handleDetail({id, name, remark}) {
            // 打开弹窗
            this.roleDialogVisibleDetail = true;
            // 获取后端返回的数据
            this.dataSourceDetail = await this.handleGetRolesByIdPermission(id, name, remark);
        },
        // 编辑
        async handleEdit({id, name, remark}) {
            // 打开弹窗
            this.roleDialogVisibleEdit = true;
            // 获取后端返回的数据
            this.dataSourceEdit = await this.handleGetRolesByIdPermission(id, name, remark);
        },
        // 删除按钮
        handleShowDeleteDialog(row) {
            console.log('row :', row);
            // 展示删除弹窗
            this.dialogVisible = true;
            this.currentRow = row;
        },
        // 删除角色
        handleDelete(row) {
            this.dialogLoading = true;
            deleteRoles(row.id)
                .then(res => {
                    this.dialogVisible = false;
                    this.$message({showClose: true, type: 'success', message: '删除成功'});
                    this.getList();
                    this.dialogLoading = false;
                })
                .catch(err => {
                    this.$message({showClose: true, type: 'error', message: '删除失败'});
                    console.log('err :', err);
                    this.dialogVisible = false;
                    this.dialogLoading = false;
                });
        }
    }
};
</script>
